//
//  Home.m
//  Sinology
//
//  Created by mac on 15/3/27.
//  Copyright (c) 2015年 mac. All rights reserved.
//

#import "photoWall.h"
#import "newsPresenter.h"

@interface photoWall ()<HMUIPhotoWallDelegate,PresenterCallBackProtocol,HMUIPhotoBrowserDatasource,HMUIPhotoBrowserDelegate>
@property (nonatomic,strong)HMUIPhotoWall *wall;
@property (nonatomic,strong)NSMutableArray *imags;
@property (nonatomic,strong)NSMutableArray *news;
@end

@implementation photoWall{
    
    NSInteger pn;
    NSInteger rn;
    int a;
}
@synthesize wall;
@synthesize imags;
@synthesize news;

- (void)dealloc
{
    self.news= nil;
    self.imags = nil;
    self.wall = nil;
    HM_SUPER_DEALLOC();
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.customNavLeftBtn setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [self.customNavLeftBtn setFrame:CGRectMakeBound(32, 32)];
    
    [self.customNavRightBtn setTitle:@"水平" forState:UIControlStateNormal];
    [self.customNavRightBtn setTitle:@"垂直" forState:UIControlStateSelected];
    [self.customNavRightBtn sizeToFit];
    self.customNavRightBtn.buttenType = UIButtenTypeAutoSelect;
    
    [self initialization];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initialization{
    self.wall = [HMUIPhotoWall spawn];
    self.wall.backgroundColor = [UIColor md_grey_200];
    self.wall.frame = self.view.bounds;
    self.wall.space = 4;
    [self.view addSubview:self.wall];
    
    [self.wall mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top).offset(0);
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
        make.right.mas_equalTo(self.view.mas_right).offset(0);
//        make.height.mas_equalTo(200);
    }];
    //    self.wall.contentInset = UIEdgeInsetsTBAndHor(50, 50, 0);
    self.wall.autoFit = YES;
    self.wall.dataSource = self;
    self.wall.delegate = self;
    self.wall.perRanks = @[@[],@[],@[],@[@(200/300.f),@(50/300.f),@(50/300.f)]];
    self.wall.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshing)];
    self.wall.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(getwallmore)];
    
    ((MJRefreshAutoFooter*)(self.wall.mj_footer)).automaticallyRefresh = YES;
    
    [self.wall.mj_header beginRefreshing];
    
    [newsPresenter sharedInstance].delegate = self;
    [[newsPresenter sharedInstance] doSomething:[newsPresenter LOADNEWS] attributes:nil];
    
}

ON_Button(signal){
    UIButten *btn = signal.source;
    if ([signal is:[UIButten TOUCH_UP_INSIDE]]) {
        if ([btn is:@"leftBtn"]) {//customNavLeftBtn
            [self backAndRemoveWithAnimate:YES];
        }else if ([btn is:@"rightBtn"]){//customNavRightBtn
                self.wall.horizontal = btn.selected;
            if (btn.selected) {
                [self.wall mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(self.view.mas_top).offset(0);
                    make.left.mas_equalTo(self.view.mas_left).offset(0);
                    //        make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
                    make.right.mas_equalTo(self.view.mas_right).offset(0);
                    make.height.mas_equalTo(200);
                }];
            }else{
                [self.wall mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(self.view.mas_top).offset(0);
                    make.left.mas_equalTo(self.view.mas_left).offset(0);
                    make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
                    make.right.mas_equalTo(self.view.mas_right).offset(0);
//                    make.height.mas_equalTo(200);
                }];
            }
//            [self.wall reloadData];
        }
    }
}

- (void)presenter:(Presenter*)presenter doSome:(NSString *)something bean:(id)bean state:(PresenterProcess)state error:(NSError *)error{
    if ([something is:[newsPresenter LOADNEWS]]) {
        if (state == PresenterProcessSucced) {
            self.news = bean;
            [self.wall reloadDataSection:0 animated:YES];
        }
        
    }
}

- (void)refreshing{
    pn = 0;
    [self getwallmore];
}

- (void)getwallmore{
    rn = 15;
    NSDictionary *para = @{@"sn":@(pn),
                           @"pn":@(rn),
                           @"ch":@"art",
                           @"cid":@"国画"};
    [[[self webApiUniqueCommand:@"http://m.image.so.com/zj" name:@"getImage" timeout:30.f]
      setWebParams:para]
     send];
}


ON_WebAPI(dlg){
    
    if (dlg.sending) {
        
        
    }else if (dlg.succeed){
        NSDictionary *dic = [dlg.output objectForKey:[HMWebAPI params]];
        if (self.imags==nil) {
            self.imags = [NSMutableArray array];
        }
        if (pn==0) {
            [self.imags removeAllObjects];
        }
        [self.imags addObjectsFromArray:[dic objectForKey:@"list"]];
        
        pn+=rn;
        if (pn==rn) {
            [self.wall reloadDataSection:3 animated:YES];
        }else{
            [self.wall appendData];
        }
        
        if ([[dic objectForKey:@"end"] boolValue]) {
            [self.wall.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.wall.mj_footer resetNoMoreData];
        }
        if ([self.wall.mj_header isRefreshing]) {
            
            [self.wall.mj_header endRefreshing];
        }else{
            [self.wall.mj_footer endRefreshing];
        }
        
        
    }else if (dlg.failed){
        if ([self.wall.mj_header isRefreshing]) {
            [self.wall.mj_header endRefreshing];
        }else{
            [self.wall.mj_footer endRefreshing];
        }
        if (dlg.timeout) {
            [self showFailureTip:@"操作失败" detail:@"链接超时" timeOut:3.f];
            return;
        }
        
        [self showFailureTip:@"网络链接失败" detail:@"数据不存在或网络错误" timeOut:3.f];
    }else if (dlg.cancelled){
        
    }
    //#if (__ON__ == __HM_DEVELOPMENT__)
    //    CC( [self.class description],dlg.responseData?dlg.responseData:dlg.errorDesc);
    //#endif	// #if (__ON__ == __BEE_DEVELOPMENT__)
}

#pragma mark -


- (void)photoWall:(HMUIPhotoWall *)browser touchInCell:(HMPhotoCell *)cell atIndexPath:(NSIndexPath*)indexPath{
    
}

-(NSUInteger)photoWallNumberOfRanks:(HMUIPhotoWall *)browser inSection:(NSInteger)section{
    if (section<3) {
        return 1;
    }
    return 3;
    
}

- (NSUInteger)photoWallRowOfCells:(HMUIPhotoWall *)browser inSection:(NSInteger)section{
    if (section<3) {
        return 1;
    }
    return self.imags.count;
}

- (NSUInteger)photoWallNumberOfSections:(HMUIPhotoWall *)browser{
    return 4;
}

- (HMPhotoItem *)photoWall:(HMUIPhotoWall *)browser itemAtIndex:(NSIndexPath *)indexPath{
    HMPhotoItem *item = [[HMPhotoItem alloc]init];
    if (indexPath.section<3) {
        item.fullScreen = YES;
        [item resetItem];
        item.indent = 0;
        item.space = 0;
        item.leading = 30;
        
        if (indexPath.section==1) {
            item.space = 4;
            item.floatScreen = YES;
            item.imageSize = browser.horizontal?CGSizeMake(50, browser.width):CGSizeMake(browser.width, 50);
        }else if(indexPath.section==0){
            item.imageSize = browser.horizontal?CGSizeMake(180, 400):CGSizeMake(400, 180);
        }else if (indexPath.section==2){
            
            item.imageSize = browser.horizontal?CGSizeMake(30, browser.width):CGSizeMake(browser.width, 30);
        }
        
        return item;
    }
    NSDictionary *data = [self.imags objectAtIndex:indexPath.row];
    CGFloat thumbnail_width = [[data objectForKey:@"cover_width"] floatValue];
    CGFloat thumbnail_height = [[data objectForKey:@"cover_height"] floatValue];
    
    [item resetItem];
    
    //这个是整个HMPhotoCell的大小，由于图片是布满整个边框的，所以名字叫imageSize
    item.imageSize = CGSizeMake(thumbnail_width, thumbnail_height);
    
    return item;
}

- (HMPhotoCell *)photoWall:(HMUIPhotoWall *)browser cellForItem:(HMPhotoItem *)item cellReload:(HMPhotoCell *)cell rect:(CGRect)rect{
    
    NSString *indentifier = @"Cell";
    switch (item.indexPath.section) {
        case 0:
            indentifier = @"scrollwCell";
            break;
        case 1:
            indentifier = @"topicCell";
            break;
        case 2:
            indentifier = @"titleCell";
            break;
        default:
            break;
    }
    if (cell==nil) {
        cell = [browser dequeueReusableCellWithIdentifier:indentifier];
        if (cell==nil) {
            cell = [[HMPhotoCell alloc]initWithReuseIdentifier:indentifier];
        }
        
    }
    
    cell.photo = item;
    
    if (item.indexPath.section<3) {
        if (item.indexPath.section==0) {
            cell.backgroundColor = [UIColor md_red_400];
//            [self setScrollCell:cell rect:rect];
        }else if (item.indexPath.section==1) {
            cell.backgroundColor = [UIColor md_red_300];
            [self setTopicCell:cell rect:rect];
        }else if (item.indexPath.section==2) {
            cell.backgroundColor = [UIColor md_red_200];
            UIScrollView *scrolll = [UIScrollView spawn];
            rect.origin = CGPointZero;
            scrolll.frame = rect;
            scrolll.backgroundColor = [UIColor md_amber_100];
            [cell addSubview:scrolll];
            scrolll.contentSize = CGSizeMake(375*2,30);
        }
        return cell;
    }
    
    NSDictionary *data = [self.imags objectAtIndex:item.indexPath.row];
//    item.webUrl =@"http://img1.gtimg.com/12/1291/129161/12916139_980x1200_0.jpg";//[data valueForKey:@"cover_imgurl"];
    item.webUrl =[data valueForKey:@"cover_imgurl"];
    cell.defaultImage = [UIImage imageNamed:@"back"];
    UILabel * label =  (id)cell.descptionView;
    label.text = [data valueForKey:@"group_title"];
    cell.imageView.gifPlay = NO;
    cell.clipsToBounds = NO;
    [cell showBackgroundShadowStyle:styleEmbossDarkLineArround];
    //要支持
    if (!item.suggestNotLoad) {
        
        [cell loadImageIfNotExist:YES];
    }
    cell.backgroundColor = item.indexPath.row%2==0?[UIColor md_amber_100]:[UIColor md_red_300];
    
    return cell;
}
#pragma mark -

- (void)setScrollCell:(HMPhotoCell*)cell rect:(CGRect)rect{
    HMUIPhotoBrowser *browser  = (id)[cell viewWithTag:120];
    if (browser==nil) {
        rect.origin = CGPointZero;
        browser = [[HMUIPhotoBrowser alloc]initWithFrame:rect];
        browser.delegate = self;
        browser.dataSource = self;
        browser.tag = 120;
        browser.allowZoom = NO;
        browser.allowAutoScroll =YES;
    }
    
    [cell addSubview:browser];
    [browser reloadData];
}

- (void)setTopicCell:(HMPhotoCell*)cell rect:(CGRect)rect{
    HMUITapbarView *bottomBar  = (id)[cell viewWithTag:120];
    
    if (bottomBar==nil) {
        rect.origin = CGPointZero;
        bottomBar= [[HMUITapbarView alloc]initWithFrame:rect];
        bottomBar.space = 5;
        bottomBar.tag = 120;
        bottomBar.backgroundColor = [UIColor whiteColor];
        bottomBar.defaultColor = [UIColor md_grey_500];
        bottomBar.slideStyle = UITapbarSlideStyleBottom;
        bottomBar.barStyle = UITapbarStyleFitSize;
        bottomBar.eventReceiver = self;
        [bottomBar addItemWithTitle:@"有问有答" imageName:nil size:CGSizeZero];
        [bottomBar addItemWithTitle:@"我的关注" imageName:nil size:CGSizeZero];
        [bottomBar addItemWithTitle:@"热门讨论" imageName:nil size:CGSizeZero];
        [bottomBar addItemWithTitle:@"积分兑换" imageName:nil size:CGSizeZero];
    }
    
    
    [cell addSubview:bottomBar];
}

#pragma mark - news

- (HMPhotoItem *)photoBrowser:(HMUIPhotoBrowser *)browser itemAtIndex:(NSUInteger)index{
    NSDictionary *detail = [self.news safeObjectAtIndex:index];
    HMPhotoItem *item = [[HMPhotoItem alloc]init];
    item.webUrl = [detail valueForKey:@"img"];
    return item;
}

- (NSUInteger)photoBrowserNumbers:(HMUIPhotoBrowser *)browser{
    return self.news.count;
}

- (void)photoBrowser:(HMUIPhotoBrowser *)photoBrowser didLoadCell:(HMPhotoCell *)cell atIndex:(NSUInteger)index{
    
}

- (void)photoBrowser:(HMUIPhotoBrowser *)photoBrowser didChangedToPageAtIndex:(NSUInteger)index{
    UILabel *label = (id)[photoBrowser viewWithTagString:@"label_News"];
    if (label==nil) {
        label = [UILabel spawn];
        [photoBrowser addSubview:label];
        [label mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(photoBrowser.mas_bottom).offset(0);
            make.height.mas_equalTo(30);
            make.left.mas_equalTo(photoBrowser.mas_left).offset(0);
            make.right.mas_equalTo(photoBrowser.mas_right).offset(0);
        }];
    }
    label.text = [[self.news objectAtIndex:index] valueForKey:@"name"];
}

- (BOOL)photoBrowser:(HMUIPhotoBrowser *)photoBrowser didTouchedIndex:(NSUInteger)index{
    
    return  NO;
}


#pragma mark -

#pragma mark 对item.suggestNotLoad的支持，不加下面的代码，item.suggestNotLoad都是NO
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    [self.wall scrollViewWillEndDragging:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self.wall scrollViewDidEndDecelerating:scrollView];
}


@end
